<template>
  <div class="page-container">
    <div class="page-header">
      <h2>数据统计</h2>
      <p>查看您的健身数据和运动记录统计</p>
    </div>

    <!-- 时间范围选择 -->
    <el-card class="filter-card">
      <div class="filter-container">
        <div class="date-picker-container">
          <span class="date-label">时间范围：</span>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="dateRangeShortcuts"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="[
              new Date(2000, 0, 1, 0, 0, 0),
              new Date(2000, 0, 1, 23, 59, 59)
            ]"
            @change="handleDateRangeChange"
          />
        </div>
        <div>
          <el-button size="small" type="primary" @click="handleDateRangeChange">刷新数据</el-button>
        </div>
      </div>
    </el-card>

    <!-- 健康数据趋势 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card v-loading="healthDataLoading" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>健康数据趋势</span>
            </div>
          </template>
          
          <div v-if="hasHealthData" class="chart-container">
            <div class="chart-wrapper">
              <div ref="weightChart" class="chart"></div>
            </div>
          </div>
          <el-empty v-else description="暂无健康数据"></el-empty>
        </el-card>
      </el-col>
    </el-row>

    <!-- 运动统计 -->
    <el-row :gutter="20">
      <el-col :md="12" :xs="24">
        <el-card v-loading="exerciseStatsLoading" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>运动时长与消耗卡路里</span>
            </div>
          </template>
          
          <div v-if="hasExerciseStats" class="chart-container">
            <div class="chart-wrapper">
              <div ref="exerciseStatsChart" class="chart"></div>
            </div>
          </div>
          <el-empty v-else description="暂无运动记录"></el-empty>
        </el-card>
      </el-col>

      <el-col :md="12" :xs="24">
        <el-card v-loading="exerciseTypeLoading" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>运动类型分布</span>
            </div>
          </template>
          
          <div v-if="hasExerciseType" class="chart-container">
            <div class="chart-wrapper">
              <div ref="exerciseTypeChart" class="chart"></div>
            </div>
          </div>
          <el-empty v-else description="暂无运动类型数据"></el-empty>
        </el-card>
      </el-col>
    </el-row>

    <!-- 目标完成情况 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card v-loading="goalsLoading" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>目标完成情况</span>
            </div>
          </template>
          
          <div v-if="hasGoals" class="chart-container goals-stats-container">
            <div class="goals-summary">
              <div class="goal-stat-item">
                <div class="goal-stat-value">{{ goalStats.total }}</div>
                <div class="goal-stat-label">总目标数</div>
              </div>
              <div class="goal-stat-item">
                <div class="goal-stat-value">{{ goalStats.active }}</div>
                <div class="goal-stat-label">进行中</div>
              </div>
              <div class="goal-stat-item">
                <div class="goal-stat-value">{{ goalStats.completed }}</div>
                <div class="goal-stat-label">已完成</div>
              </div>
              <div class="goal-stat-item">
                <div class="goal-stat-value">{{ goalStats.failed }}</div>
                <div class="goal-stat-label">未达成</div>
              </div>
            </div>
            
            <div class="chart-wrapper">
              <div ref="goalsChart" class="chart"></div>
            </div>
          </div>
          <el-empty v-else description="暂无目标数据"></el-empty>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getHealthDataByDateRange } from '@/api/healthData'
import { getExerciseRecordsByDateRange, getExerciseStats } from '@/api/exerciseRecord'
import { getFitnessGoals } from '@/api/fitnessGoal'

// 图表引用
const weightChart = ref(null)
const exerciseStatsChart = ref(null)
const exerciseTypeChart = ref(null)
const goalsChart = ref(null)

// 加载状态
const healthDataLoading = ref(false)
const exerciseStatsLoading = ref(false)
const exerciseTypeLoading = ref(false)
const goalsLoading = ref(false)

// 是否有数据
const hasHealthData = ref(false)
const hasExerciseStats = ref(false)
const hasExerciseType = ref(false)
const hasGoals = ref(false)

// 数据容器
const healthDataList = ref([])
const exerciseStats = reactive({
  dates: [],
  durations: [],
  calories: []
})
const exerciseTypeData = ref([])
const goals = ref([])

// 目标统计
const goalStats = reactive({
  total: 0,
  active: 0,
  completed: 0,
  failed: 0
})

// 日期范围
const dateRange = ref([])
const dateRangeShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 图表实例
let weightChartInstance = null
let exerciseStatsChartInstance = null
let exerciseTypeChartInstance = null
let goalsChartInstance = null

// 处理日期范围变化
const handleDateRangeChange = () => {
  if (dateRange.value && dateRange.value.length === 2) {
    console.log('选择的日期范围:', {
      开始日期: dateRange.value[0],
      结束日期: dateRange.value[1]
    });
    
    fetchHealthData()
    fetchExerciseRecords()
  }
}

// 获取健康数据
const fetchHealthData = async () => {
  if (!dateRange.value || !dateRange.value[0] || !dateRange.value[1]) return
  
  healthDataLoading.value = true
  
  try {
    console.log('请求健康数据，日期范围:', dateRange.value)
    const startDate = typeof dateRange.value[0] === 'string' ? dateRange.value[0] : dateRange.value[0].toISOString().slice(0, 19).replace('T', ' ')
    const endDate = typeof dateRange.value[1] === 'string' ? dateRange.value[1] : dateRange.value[1].toISOString().slice(0, 19).replace('T', ' ')
    
    console.log('格式化后的日期范围:', { startDate, endDate })
    const response = await getHealthDataByDateRange(startDate, endDate)
    console.log('健康数据响应:', response)
    
    // 正确处理响应数据
    if (response) {
      // 根据返回的数据结构决定如何提取数据
      if (response.data && Array.isArray(response.data)) {
        healthDataList.value = response.data
        console.log('提取响应中的data数组，长度:', healthDataList.value.length)
      } else if (Array.isArray(response)) {
        healthDataList.value = response
        console.log('响应本身是数组，长度:', healthDataList.value.length)
      } else if (typeof response === 'object') {
        // 查找对象中的数组属性
        const arrayProps = Object.entries(response)
          .filter(([_, val]) => Array.isArray(val))
          .map(([key, val]) => ({ key, length: val.length }))
        
        console.log('响应对象中的数组属性:', arrayProps)
        
        // 使用找到的第一个数组属性，或返回空数组
        const firstArrayProp = Object.entries(response)
          .find(([_, val]) => Array.isArray(val))
        
        if (firstArrayProp) {
          healthDataList.value = firstArrayProp[1]
          console.log(`使用响应中的${firstArrayProp[0]}属性，长度:`, healthDataList.value.length)
        } else {
          healthDataList.value = []
          console.log('未找到数组数据，使用空数组')
        }
      } else {
        healthDataList.value = []
        console.log('未识别的响应格式，使用空数组')
      }
      
      // 按日期排序
      healthDataList.value.sort((a, b) => {
        return new Date(a.recordDate) - new Date(b.recordDate)
      })
      console.log('排序后的健康数据:', healthDataList.value)
      
      hasHealthData.value = healthDataList.value.length > 0
      console.log('健康数据是否存在:', hasHealthData.value)
      
      if (hasHealthData.value) {
        console.log('健康数据示例:', healthDataList.value[0])
        // 在下一个渲染周期初始化图表
        nextTick(() => {
          initWeightChart()
        })
      }
    } else {
      console.log('没有获取到健康数据')
      hasHealthData.value = false
    }
  } catch (error) {
    console.error('获取健康数据失败:', error)
    ElMessage.error('获取健康数据失败: ' + (error.message || error))
    hasHealthData.value = false
  } finally {
    healthDataLoading.value = false
  }
}

// 获取运动记录
const fetchExerciseRecords = async () => {
  if (!dateRange.value || !dateRange.value[0] || !dateRange.value[1]) return
  
  exerciseStatsLoading.value = true
  exerciseTypeLoading.value = true
  
  try {
    console.log('请求运动记录，日期范围:', dateRange.value)
    const startDate = typeof dateRange.value[0] === 'string' ? dateRange.value[0] : dateRange.value[0].toISOString().slice(0, 19).replace('T', ' ')
    const endDate = typeof dateRange.value[1] === 'string' ? dateRange.value[1] : dateRange.value[1].toISOString().slice(0, 19).replace('T', ' ')
    
    console.log('格式化后的日期范围:', { startDate, endDate })
    const response = await getExerciseRecordsByDateRange(startDate, endDate)
    console.log('运动记录响应:', response)
    
    // 创建一个单独的变量存储运动记录
    let exerciseRecords = []
    
    if (response) {
      // 根据返回的数据结构决定如何提取数据
      if (response.data && Array.isArray(response.data)) {
        exerciseRecords = response.data
        console.log('提取响应中的data数组，长度:', exerciseRecords.length)
      } else if (Array.isArray(response)) {
        exerciseRecords = response
        console.log('响应本身是数组，长度:', exerciseRecords.length)
      } else if (typeof response === 'object') {
        // 查找对象中的数组属性
        const arrayProps = Object.entries(response)
          .filter(([_, val]) => Array.isArray(val))
          .map(([key, val]) => ({ key, length: val.length }))
        
        console.log('响应对象中的数组属性:', arrayProps)
        
        // 使用找到的第一个数组属性，或返回空数组
        const firstArrayProp = Object.entries(response)
          .find(([_, val]) => Array.isArray(val))
        
        if (firstArrayProp) {
          exerciseRecords = firstArrayProp[1]
          console.log(`使用响应中的${firstArrayProp[0]}属性，长度:`, exerciseRecords.length)
        } else {
          exerciseRecords = []
          console.log('未找到数组数据，使用空数组')
        }
      } else {
        exerciseRecords = []
        console.log('未识别的响应格式，使用空数组')
      }
      
      // 按日期排序
      exerciseRecords.sort((a, b) => {
        return new Date(a.startTime || a.recordDate) - new Date(b.startTime || b.recordDate)
      })
      console.log('排序后的运动记录:', exerciseRecords)
      
      hasExerciseStats.value = exerciseRecords.length > 0
      console.log('运动记录是否存在:', hasExerciseStats.value)
      
      if (hasExerciseStats.value) {
        console.log('运动记录示例:', exerciseRecords[0])
        
        // 处理运动记录数据 - 使用正确的数据源
        processExerciseRecords(exerciseRecords)
        
        // 获取运动类型分布
        await fetchExerciseTypeDistribution()
        
        hasExerciseType.value = exerciseTypeData.value.length > 0
        
        // 获取健身目标
        await fetchGoals()
        
        // 初始化图表
        nextTick(() => {
          initExerciseCharts()
        })
      } else {
        hasExerciseStats.value = false
        hasExerciseType.value = false
      }
    } else {
      console.log('没有获取到运动记录')
      hasExerciseStats.value = false
      hasExerciseType.value = false
    }
  } catch (error) {
    console.error('获取运动记录失败:', error)
    ElMessage.error('获取运动记录失败: ' + (error.message || error))
    hasExerciseStats.value = false
    hasExerciseType.value = false
  } finally {
    exerciseStatsLoading.value = false
    exerciseTypeLoading.value = false
  }
}

// 获取目标数据
const fetchGoals = async () => {
  goalsLoading.value = true
  
  try {
    const response = await getFitnessGoals()
    
    if (response && response.length > 0) {
      goals.value = response
      
      // 统计目标状态
      const statusCount = {
        ACTIVE: 0,
        COMPLETED: 0,
        FAILED: 0,
        ABANDONED: 0,
        OVERDUE: 0  // 新增：逾期但未关闭的目标
      }
      
      const currentDate = new Date()
      
      response.forEach(goal => {
        // 检查目标是否已逾期但仍标记为活跃
        if (goal.status === 'ACTIVE') {
          // 检查目标是否有结束日期
          if (goal.endDate || goal.targetDate) {
            const targetDate = new Date(goal.endDate || goal.targetDate)
            
            // 判断是否已逾期
            if (targetDate < currentDate) {
              // 已逾期但仍标记为活跃的目标
              statusCount.OVERDUE++
            } else {
              // 真正活跃的目标
              statusCount.ACTIVE++
            }
          } else {
            // 没有结束日期的目标保持活跃状态
            statusCount.ACTIVE++
          }
        } else if (statusCount[goal.status] !== undefined) {
          // 其他状态正常计数
          statusCount[goal.status]++
        }
      })
      
      goalStats.total = response.length
      goalStats.active = statusCount.ACTIVE
      goalStats.completed = statusCount.COMPLETED
      // 将逾期目标计入未达成类别
      goalStats.failed = statusCount.FAILED + statusCount.ABANDONED + statusCount.OVERDUE
      
      // 按类型统计目标
      const typeCount = {}
      
      response.forEach(goal => {
        if (!typeCount[goal.type]) {
          typeCount[goal.type] = { total: 0, completed: 0 }
        }
        
        typeCount[goal.type].total++
        
        if (goal.status === 'COMPLETED') {
          typeCount[goal.type].completed++
        }
      })
      
      hasGoals.value = true
      
      nextTick(() => {
        initGoalsChart(typeCount)
      })
    } else {
      hasGoals.value = false
    }
  } catch (error) {
    console.error('获取目标数据失败:', error)
    ElMessage.error('获取目标数据失败')
    hasGoals.value = false
  } finally {
    goalsLoading.value = false
  }
}

// 初始化健康数据图表
const initWeightChart = () => {
  if (!weightChart.value) {
    console.error('图表DOM元素不存在，无法初始化体重图表')
    return
  }
  
  // 清除旧图表
  if (weightChartInstance) {
    weightChartInstance.dispose()
  }
  
  console.log('开始初始化体重图表，数据长度:', healthDataList.value.length)
  
  // 创建图表实例
  weightChartInstance = echarts.init(weightChart.value)
  
  // 准备数据
  const dates = healthDataList.value.map(item => item.recordDate.split(' ')[0])
  const weights = healthDataList.value.map(item => item.weight)
  const bmiData = healthDataList.value.map(item => item.bmi)
  const heartRates = healthDataList.value.map(item => item.restingHeartRate)
  
  console.log('图表数据:', {
    日期: dates,
    体重: weights,
    BMI: bmiData,
    心率: heartRates
  })
  
  // 设置图表配置
  const option = {
    title: {
      text: '健康数据趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      formatter: function(params) {
        let result = params[0].axisValue + '<br/>';
        params.forEach(item => {
          let value = item.value;
          if (item.seriesName.includes('体重')) {
            value += ' kg';
          } else if (item.seriesName.includes('BMI')) {
            value = value ? value.toFixed(1) : '无数据';
          } else if (item.seriesName.includes('心率')) {
            value += ' bpm';
          }
          result += `${item.marker} ${item.seriesName}: ${value}<br/>`;
        });
        return result;
      }
    },
    legend: {
      data: ['体重 (kg)', 'BMI', '静息心率 (bpm)'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates,
      boundaryGap: false,
      axisLabel: {
        formatter: (value) => {
          return value.substring(5); // 只显示月-日部分
        },
        rotate: dates.length > 10 ? 30 : 0
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '体重 (kg)',
        position: 'left',
        axisLine: {
          show: true,
          lineStyle: {
            color: '#5470C6'
          }
        },
        axisLabel: {
          formatter: '{value} kg'
        }
      },
      {
        type: 'value',
        name: 'BMI / 心率 (bpm)',
        position: 'right',
        axisLine: {
          show: true,
          lineStyle: {
            color: '#91CC75'
          }
        }
      }
    ],
    series: [
      {
        name: '体重 (kg)',
        type: 'line',
        data: weights,
        yAxisIndex: 0,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 3
        },
        connectNulls: true,
        emphasis: {
          focus: 'series'
        },
        markLine: {
          data: [
            { 
              type: 'average', 
              name: '平均体重',
              label: {
                formatter: '{b}: {c} kg'
              }
            }
          ]
        }
      },
      {
        name: 'BMI',
        type: 'line',
        data: bmiData,
        yAxisIndex: 1,
        symbol: 'rect',
        symbolSize: 8,
        lineStyle: {
          width: 3
        },
        connectNulls: true,
        emphasis: {
          focus: 'series'
        }
      },
      {
        name: '静息心率 (bpm)',
        type: 'line',
        data: heartRates,
        yAxisIndex: 1,
        symbol: 'triangle',
        symbolSize: 8,
        lineStyle: {
          width: 3
        },
        connectNulls: true,
        emphasis: {
          focus: 'series'
        }
      }
    ]
  }
  
  try {
    // 渲染图表
    weightChartInstance.setOption(option)
    console.log('体重图表初始化成功')
    
    // 响应窗口大小变化
    window.addEventListener('resize', () => {
      if (weightChartInstance) {
        weightChartInstance.resize()
      }
    })
  } catch (error) {
    console.error('渲染体重图表失败:', error)
  }
}

// 处理运动记录数据
const processExerciseRecords = (records) => {
  if (!records || records.length === 0) {
    exerciseStats.dates = []
    exerciseStats.durations = []
    exerciseStats.calories = []
    return
  }
  
  // 按日期分组
  const recordsByDate = {}
  
  records.forEach(record => {
    const date = (record.startTime || record.recordDate).split(' ')[0]
    if (!recordsByDate[date]) {
      recordsByDate[date] = {
        duration: 0,
        calories: 0
      }
    }
    recordsByDate[date].duration += record.durationMinutes || 0
    recordsByDate[date].calories += record.caloriesBurned || 0
  })
  
  console.log('按日期分组后的运动记录:', recordsByDate)
  
  // 转换为图表数据
  exerciseStats.dates = Object.keys(recordsByDate).sort()
  exerciseStats.durations = exerciseStats.dates.map(date => recordsByDate[date].duration)
  exerciseStats.calories = exerciseStats.dates.map(date => recordsByDate[date].calories)
  
  console.log('处理后的运动统计数据:', exerciseStats)
}

// 获取运动类型分布
const fetchExerciseTypeDistribution = async () => {
  try {
    const response = await getExerciseStats()
    if (response && response.typeDistribution) {
      exerciseTypeData.value = Object.entries(response.typeDistribution).map(([name, value]) => ({
        name,
        value
      }))
    }
  } catch (error) {
    console.error('获取运动类型分布失败:', error)
  }
}

// 初始化运动图表
const initExerciseCharts = () => {
  initExerciseStatsChart()
  initExerciseTypeChart()
}

// 初始化运动统计图表
const initExerciseStatsChart = () => {
  if (!exerciseStatsChart.value) return
  
  // 清除旧图表
  if (exerciseStatsChartInstance) {
    exerciseStatsChartInstance.dispose()
  }
  
  console.log('开始初始化运动统计图表，数据长度:', exerciseStats.dates.length)
  
  // 创建图表实例
  exerciseStatsChartInstance = echarts.init(exerciseStatsChart.value)
  
  // 设置图表配置
  const option = {
    title: {
      text: '运动时长与消耗卡路里',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      formatter: function(params) {
        let result = params[0].axisValue + '<br/>';
        params.forEach(item => {
          let value = item.value;
          if (item.seriesName.includes('时长')) {
            value += ' 分钟';
          } else if (item.seriesName.includes('卡路里')) {
            value += ' kcal';
          }
          result += `${item.marker} ${item.seriesName}: ${value}<br/>`;
        });
        return result;
      }
    },
    legend: {
      data: ['运动时长 (分钟)', '消耗卡路里 (kcal)'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: exerciseStats.dates,
      boundaryGap: true,
      axisLabel: {
        formatter: (value) => {
          // 只显示月-日部分，使日期更简洁
          return value.substring(5);
        },
        rotate: exerciseStats.dates.length > 10 ? 30 : 0
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '运动时长 (分钟)',
        position: 'left',
        axisLine: {
          show: true,
          lineStyle: {
            color: '#5470C6'
          }
        },
        axisLabel: {
          formatter: '{value} 分钟'
        }
      },
      {
        type: 'value',
        name: '消耗卡路里 (kcal)',
        position: 'right',
        axisLine: {
          show: true,
          lineStyle: {
            color: '#EE6666'
          }
        },
        axisLabel: {
          formatter: '{value} kcal'
        }
      }
    ],
    series: [
      {
        name: '运动时长 (分钟)',
        type: 'bar',
        data: exerciseStats.durations,
        yAxisIndex: 0,
        itemStyle: {
          color: '#5470C6'
        },
        emphasis: {
          focus: 'series'
        },
        markLine: {
          data: [
            { 
              type: 'average', 
              name: '平均时长',
              label: {
                formatter: '{b}: {c} 分钟'
              }
            }
          ]
        }
      },
      {
        name: '消耗卡路里 (kcal)',
        type: 'line',
        data: exerciseStats.calories,
        yAxisIndex: 1,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 3
        },
        itemStyle: {
          color: '#EE6666'
        },
        emphasis: {
          focus: 'series'
        },
        markLine: {
          data: [
            { 
              type: 'average', 
              name: '平均卡路里',
              label: {
                formatter: '{b}: {c} kcal'
              }
            }
          ]
        }
      }
    ]
  }
  
  try {
    // 渲染图表
    exerciseStatsChartInstance.setOption(option)
    console.log('运动统计图表初始化成功')
    
    // 响应窗口大小变化
    window.addEventListener('resize', () => {
      if (exerciseStatsChartInstance) {
        exerciseStatsChartInstance.resize()
      }
    })
  } catch (error) {
    console.error('渲染运动统计图表失败:', error)
  }
}

// 初始化运动类型分布图表
const initExerciseTypeChart = () => {
  if (!exerciseTypeChart.value) return
  
  // 清除旧图表
  if (exerciseTypeChartInstance) {
    exerciseTypeChartInstance.dispose()
  }
  
  // 创建图表实例
  exerciseTypeChartInstance = echarts.init(exerciseTypeChart.value)
  
  // 设置图表配置
  const option = {
    title: {
      text: '运动类型分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      type: 'scroll',
      orient: 'horizontal',
      bottom: 10,
      data: exerciseTypeData.value.map(item => item.name)
    },
    color: ['#5470C6', '#91CC75', '#EE6666', '#FAC858', '#73C0DE', '#3BA272', '#FC8452', '#9A60B4'],
    series: [
      {
        name: '运动类型',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {d}%'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        labelLine: {
          show: true
        },
        data: exerciseTypeData.value
      }
    ]
  }
  
  // 渲染图表
  exerciseTypeChartInstance.setOption(option)
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    exerciseTypeChartInstance.resize()
  })
}

// 初始化目标图表
const initGoalsChart = (typeCount) => {
  if (!goalsChart.value) return
  
  // 清除旧图表
  if (goalsChartInstance) {
    goalsChartInstance.dispose()
  }
  
  // 处理数据
  const types = Object.keys(typeCount)
  const seriesData = types.map(type => {
    const getTypeDisplayName = (type) => {
      const typeMap = {
        'WEIGHT_LOSS': '减重目标',
        'EXERCISE_FREQUENCY': '运动频率',
        'DISTANCE': '距离目标',
        'STRENGTH': '力量目标',
        'ENDURANCE': '耐力目标',
        'CUSTOM': '自定义'
      }
      return typeMap[type] || type
    }
    
    return {
      type: getTypeDisplayName(type),
      total: typeCount[type].total,
      completed: typeCount[type].completed
    }
  })
  
  // 创建图表实例
  goalsChartInstance = echarts.init(goalsChart.value)
  
  // 设置图表配置
  const option = {
    title: {
      text: '目标完成情况 (按类型)',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        const type = params[0].axisValue;
        let total = 0;
        let completed = 0;
        
        params.forEach(item => {
          if (item.seriesName === '目标总数') {
            total = item.value;
          } else if (item.seriesName === '已完成') {
            completed = item.value;
          }
        });
        
        const ratio = total > 0 ? (completed / total * 100).toFixed(1) : 0;
        
        let result = `${type}<br/>`;
        params.forEach(item => {
          result += `${item.marker} ${item.seriesName}: ${item.value}<br/>`;
        });
        result += `<span style="display:inline-block;margin-right:4px;border-radius:10px;width:10px;height:10px;background-color:#91CC75;"></span> 完成率: ${ratio}%`;
        
        return result;
      }
    },
    legend: {
      data: ['目标总数', '已完成'],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: seriesData.map(item => item.type),
      axisLabel: {
        rotate: seriesData.length > 5 ? 30 : 0,
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      name: '目标数量',
      minInterval: 1
    },
    series: [
      {
        name: '目标总数',
        type: 'bar',
        barMaxWidth: 50,
        itemStyle: {
          color: '#5470C6'
        },
        emphasis: {
          focus: 'series'
        },
        data: seriesData.map(item => item.total)
      },
      {
        name: '已完成',
        type: 'bar',
        barMaxWidth: 50,
        itemStyle: {
          color: '#91CC75'
        },
        emphasis: {
          focus: 'series'
        },
        data: seriesData.map(item => item.completed),
        label: {
          show: true,
          position: 'top',
          formatter: (params) => {
            const typeIndex = seriesData.findIndex(item => item.type === params.name);
            if (typeIndex !== -1) {
              const total = seriesData[typeIndex].total;
              const ratio = total > 0 ? (params.value / total * 100).toFixed(0) : 0;
              return `${ratio}%`;
            }
            return '';
          }
        }
      }
    ]
  }
  
  // 渲染图表
  goalsChartInstance.setOption(option)
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    goalsChartInstance.resize()
  })
}

// 初始化默认日期范围（最近一周）
const initDefaultDateRange = () => {
  const end = new Date()
  const start = new Date()
  start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
  
  // 格式化为"YYYY-MM-DD HH:mm:ss"格式
  const formatDate = (date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }
  
  const startFormatted = formatDate(start)
  const endFormatted = formatDate(end)
  
  console.log('格式化的日期范围:', { startFormatted, endFormatted })
  
  dateRange.value = [startFormatted, endFormatted]
}

// 组件挂载时执行
onMounted(async () => {
  console.log('统计组件挂载');
  
  // 先初始化日期范围
  initDefaultDateRange();
  console.log('初始化默认日期范围:', dateRange.value);
  
  // 等待一下确保日期范围设置完成
  await nextTick();
  
  try {
    // 分别获取各类数据
    console.log('开始获取数据...');
    await fetchHealthData().catch(err => {
      console.error('获取健康数据失败:', err);
      ElMessage.warning('获取健康数据失败，请稍后重试');
    });
    
    await fetchExerciseRecords().catch(err => {
      console.error('获取运动记录失败:', err);
      ElMessage.warning('获取运动记录失败，请稍后重试');
    });
    
    await fetchGoals().catch(err => {
      console.error('获取目标数据失败:', err);
      ElMessage.warning('获取目标数据失败，请稍后重试');
    });
    
    console.log('数据获取完成');
  } catch (error) {
    console.error('初始化数据发生错误:', error);
    ElMessage.error('加载统计数据失败');
  }
})
</script>

<style scoped>
.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 10px 0;
  font-weight: 500;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.date-picker-container {
  display: flex;
  align-items: center;
}

.date-label {
  margin-right: 10px;
  white-space: nowrap;
  color: #606266;
}

.chart-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  display: flex;
  flex-direction: column;
}

.chart-wrapper {
  width: 100%;
}

.chart {
  width: 100%;
  height: 400px;
}

.goals-stats-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.goals-summary {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  margin-bottom: 20px;
}

.goal-stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  min-width: 120px;
  margin: 5px;
}

.goal-stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.goal-stat-label {
  margin-top: 5px;
  color: #606266;
  font-size: 14px;
}

@media (max-width: 768px) {
  .filter-container {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .date-picker-container {
    width: 100%;
    margin-bottom: 10px;
  }
  
  .chart {
    height: 300px;
  }
}
</style> 